package com.learn.excel.core.util;

import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Decoder;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author anri
 * @date 2021/1/24 9:59
 */
@Slf4j
public class EncryptUtil {
    /**
     *AES解密
     *
     *@paramsSrc
     *@paramsKey
     *@return
     *@throwsException
     */
    public static String decryptByAes1(String sSrc,String sKey,String vi)throws Exception{
        try{
//判断Key是否正确
            if(sKey==null){
                System.out.print("Key为空null");
                return null;
            }
//判断Key是否为16位
            if(sKey.length()!=16){
                System.out.print("Key长度不是16位");
                return null;
            }
            byte[]raw=sKey.getBytes("ASCII");
            SecretKeySpec skeySpec=new SecretKeySpec(raw,"AES");
            Cipher cipher= Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv=new IvParameterSpec(vi.getBytes());
            cipher.init(Cipher.DECRYPT_MODE,skeySpec,iv);
            byte[]encrypted1=new BASE64Decoder().decodeBuffer(sSrc);//先用base64解密
            try{
                byte[]original=cipher.doFinal(encrypted1);
                String originalString=new String(original);
                return originalString;
            }catch(Exception e){
                System.out.println("EncryptUtil-->decryptByAesAES解密失败！"+e);
                return null;
            }
        }catch(Exception ex){
            System.out.println("EncryptUtil-->decryptByAesAES解密失败！"+ex);
            return null;
        }
    }
    /**
     *AES解密
     *
     *@paramsSrc
     *@paramsKey
     *@return
     *@throwsException
     */
    public static String decryptByAes(String sSrc,String sKey,String vi)throws Exception{
    try{
//判断Key是否正确
        if(sKey==null){
            System.out.print("Key为空null");
            return null;
        }
//判断Key是否为16位
        if(sKey.length()!=16){
            System.out.print("Key长度不是16位");
            return null;
        }
        byte[]raw=sKey.getBytes("ASCII");
        SecretKeySpec skeySpec=new SecretKeySpec(raw,"AES");
        Cipher cipher=Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec iv=new IvParameterSpec(vi.getBytes());
        cipher.init(Cipher.DECRYPT_MODE,skeySpec,iv);
        byte[]encrypted1=new BASE64Decoder().decodeBuffer(sSrc);//先用base64解密
        try{
            byte[]original=cipher.doFinal(encrypted1);
            String originalString=new String(original);
            return originalString;
        }catch(Exception e){
            System.out.println("EncryptUtil-->decryptByAesAES解密失败！"+e);
            return null;
        }
    }catch(Exception ex){
        System.out.println("EncryptUtil-->decryptByAesAES解密失败！"+ex);
        return null;
    }
}
}
